package com.mxm.mirai.bot;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mxm.mirai.service.BotgroupsService;
import net.dreamlu.mica.http.HttpRequest;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.GroupMessageEvent;
import net.mamoe.mirai.message.data.LightApp;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
@Component
public class BotMusic163 implements Consumer<GroupMessageEvent> {

    @Autowired
    BotgroupsService botgroupsService;
    private static BotMusic163 botMusic163;
    @PostConstruct
    public void init(){
        botMusic163=this;
        botMusic163.botgroupsService = this.botgroupsService;
    }
    private static final SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");

//    public static final AtomicBoolean isRunning = new AtomicBoolean(false);
//
//    public static final AtomicReference<Long> runningQQ = new AtomicReference(0L);
//
//    public static final AtomicReference<Long> runningGroup = new AtomicReference(0L);

    private static Map<String,Object> mapdata=null;

    private static StringBuffer buffer=null;

    private static BotMusic163Data botMusic163Data = new BotMusic163Data();

    private static Map<String,Object> QQIdGroupId=new HashMap();

//    public static int step = 0;

    @Override
    public void accept(GroupMessageEvent event) {
        if("0".equals(botMusic163.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()),String.valueOf(event.getGroup().getId()),"BotMusic163"))){return;}
        Group group = event.getGroup();//群类
        String message = event.getMessage().contentToString();//群消息
        long groupId = group.getId();//群号
        long qq = event.getSender().getId();//群发送人号
        botMusic163Data = (BotMusic163Data) QQIdGroupId.get(qq+""+groupId);
        botMusic163Data=botMusic163Data==null?botMusic163Data=new BotMusic163Data():botMusic163Data;
        botMusic163Data.setRunning(true);
        botMusic163Data.setRunningQQ(qq);
        botMusic163Data.setRunningGroup(groupId);
        if (message.length() > 2 && "点歌".equals(message.substring(0,2))) {
            try{
                botMusic163Data.setStep(1);
                QQIdGroupId.put(qq+""+groupId,botMusic163Data);
                group.sendMessage(getMusic163A(message.substring(2,message.length())));
            }catch (Exception e){
                botMusic163Data.setStep(0);
            }
//            stepA(group,groupId,qq,message);
        }else if(botMusic163Data.getStep() == 1){
            stepB(group,qq, message);
        }
//        switch (step) {//初始值0
//            case 0:
//                stepA(group, groupId, qq, message);
//                break;
//            case 1:
//                stepB(group, qq, message);
//                break;
//            default:
//                break;
//        }
    }
    private void stepA(Group api, long groupId, long qq, String message) {
        if (message.length() > 2 && "点歌".equals(message.substring(0,2))) {
            botMusic163Data = new BotMusic163Data();
            try{
                botMusic163Data.setStep(1);
                QQIdGroupId.put(qq+""+groupId,botMusic163Data);
                api.sendMessage(getMusic163A(message.substring(2,message.length())));
            }catch (Exception e){
                botMusic163Data.setStep(0);
            }
       }
    }
    private void stepB(Group group,long qq, String message) {
        if (qq != botMusic163Data.getRunningQQ() || group.getId()!=botMusic163Data.getRunningGroup()) {return; }
        botMusic163Data.setStep(0);
        if (isNumeric(message)) {
            try {
                Map map = (Map) botMusic163Data.getMapdata().get(message);
                String mp3 = getMusic163mp3url(map.get("id").toString()).replace("http://","").replace("https://","");
                String img_ion = getMusic163Imgurl(map.get("id").toString()).replace("http://","").replace("https://","");
                MusicJSON musicJSON = new MusicJSON();
                MusicJSON.ConfigBean configBean = new MusicJSON.ConfigBean();
                MusicJSON.MetaBean metaBean = new MusicJSON.MetaBean();
                MusicJSON.MetaBean.MusicBean musicBean = new MusicJSON.MetaBean.MusicBean();
                musicJSON.setPrompt("[分享]网易音乐-"+map.get("name"));
                musicBean.setTitle((String) map.get("name"));
                musicBean.setDesc(map.get("artist")+"-"+map.get("album"));
                musicBean.setPreview(img_ion);
                musicBean.setTag("网易音乐-"+map.get("time"));
                musicBean.setMusicUrl(mp3);
                musicBean.setJumpUrl("");
                musicBean.setAppid(101097681);
                musicBean.setApp_type(1);
                musicBean.setSource_url("");
                musicBean.setSource_icon(img_ion);
                musicBean.setAndroid_pkg_name("com.tencent.karaoke");
                configBean.setForward(true);
                configBean.setNormal("normal");
                configBean.setAutosize(true);
                metaBean.setMusic(musicBean);
                musicJSON.setMeta(metaBean);
                musicJSON.setConfig(configBean);
                group.sendMessage(new LightApp(new GsonBuilder().disableHtmlEscaping().create().toJson(musicJSON)));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取歌曲封面图片
     * @param id
     * @return
     */
    private static String getMusic163Imgurl(String id){
        String html = HttpRequest.get("http://music.163.com/api/song/detail/?id="+id+"&ids=%5B"+id+"%5D")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(120))
                .execute().asString();
        return StringUtils.substringBetween(html, "\"blurPicUrl\":\"", "\",\"companyId\":");
    }

    /**
     * 获取歌曲mp3文
     * @param id
     * @return
     */
    private static String getMusic163mp3url(String id){
        String html = HttpRequest.get("http://music.163.com/api/song/enhance/player/url?id="+id+"&ids=["+id+"]&br=3200000")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(120))
                .execute().asString();
        return StringUtils.substringBetween(html, ",\"url\":\"", "\",\"br\":");
    }
    private static String getMusic163A(String name){
        RequestBody body = new FormBody.Builder()
                .add("s",name)
                .add("hlpretag","<span class=\"s-fc7\">")
                .add("hlposttag","</span>")
                .add("type","1")
                .add("offset","0")
                .add("total","true")
                .add("limit","12")
                .build();
        String text = "",time = "",html = "";
        try{
        html = HttpRequest.post("http://music.163.com/api/search/get/web?csrf_token=")
                .body(body)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(120))
                .execute()
                .asString();
        }catch (Exception e){
            return "音乐搜索失败！";
        }
        com.mxm.mirai.dao.BotMusic163 music=new Gson().fromJson(html, com.mxm.mirai.dao.BotMusic163.class);
        mapdata = new HashMap();
        Map map=null;
        int index = 0;
        for (com.mxm.mirai.dao.BotMusic163.ResultBean.SongsBean songs:music.getResult().getSongs()) {
            map=new HashMap();
            //System.out.println(songs.getId()+"___"+songs.getName()+"___"+songs.getArtists().get(0).getName()+"___"+songs.getDuration()+"___"+songs.getAlbum().getName());
            index+=1;
            time = StampByTime(songs.getDuration());
            text+=index+"."+songs.getName()+"\n["+songs.getArtists().get(0).getName()+"]["+time+"]\n";
            map.put("id",songs.getId());
            map.put("name",songs.getName());
            map.put("artist",songs.getArtists().get(0).getName());
            map.put("time",time);
            map.put("album",songs.getAlbum().getName());
            mapdata.put(String.valueOf(index),map);
        }
        botMusic163Data.setMapdata(mapdata);
        return "".equals(text)?"视频搜索失败！":text+"[回复数字可快捷选择]";
    }
    /**
     * 时间戳转换时间
     * @param stamp
     * @return
     */
    public static String StampByTime(int stamp){
        try{
            return sdf.format(new Date(stamp)); // 时间戳转换日期
        }catch (Exception e){
            return "获取失败"; // 时间戳转换日期
        }
    }
    /**
     * 判断字符是否为整数
     * @param str
     * @return
     */
    private static boolean isNumeric(String str){
        for (int i = 0; i < str.length(); i++){
            //System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }
}
class BotMusic163Data{
    private Boolean isRunning;
    private Long runningQQ;
    private Long runningGroup;
    private Integer step = 0;
    private Map<String,Object> mapdata;

    public Boolean getRunning() {
        return isRunning;
    }

    public void setRunning(Boolean running) {
        isRunning = running;
    }

    public Long getRunningQQ() {
        return runningQQ;
    }

    public void setRunningQQ(Long runningQQ) {
        this.runningQQ = runningQQ;
    }

    public Long getRunningGroup() {
        return runningGroup;
    }

    public void setRunningGroup(Long runningGroup) {
        this.runningGroup = runningGroup;
    }

    public Integer getStep() {
        return step;
    }

    public void setStep(Integer step) {
        this.step = step;
    }

    public Map<String, Object> getMapdata() {
        return mapdata;
    }

    public void setMapdata(Map<String, Object> mapdata) {
        this.mapdata = mapdata;
    }
}
class MusicJSON{

    /**
     * app : com.tencent.structmsg
     * desc : 音乐
     * view : music
     * ver : 0.0.0.1
     * prompt : [分享]网易音乐-童话
     * meta : {"music":{"title":"童话","desc":"光良-童话","preview":"p2.music.126.net/Lezq2-nYThXCmjJ8im18TA==/18809345418066555.jpg","tag":"网易音乐-04:04","musicUrl":"music.163.com/song/media/outer/url?id=85580.mp3","jumpUrl":"music.163.com/song/media/outer/url?id=85580.mp3","appid":101097681,"app_type":1,"source_url":"music.163.com/song/media/outer/url?id=85580.mp3","source_icon":"p2.music.126.net/Lezq2-nYThXCmjJ8im18TA==/18809345418066555.jpg","android_pkg_name":"com.tencent.karaoke"}}
     * config : {"forward":true,"normal":"normal","autosize":true}
     */

    private String app="com.tencent.structmsg";
    private String desc="音乐";
    private String view="music";
    private String ver="0.0.0.1";
    private String prompt="[分享]网易音乐-童话";
    private MetaBean meta;
    private ConfigBean config;

    public String getApp() {
        return app;
    }

    public void setApp(String app) {
        this.app = app;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getView() {
        return view;
    }

    public void setView(String view) {
        this.view = view;
    }

    public String getVer() {
        return ver;
    }

    public void setVer(String ver) {
        this.ver = ver;
    }

    public String getPrompt() {
        return prompt;
    }

    public void setPrompt(String prompt) {
        this.prompt = prompt;
    }

    public MetaBean getMeta() {
        return meta;
    }

    public void setMeta(MetaBean meta) {
        this.meta = meta;
    }

    public ConfigBean getConfig() {
        return config;
    }

    public void setConfig(ConfigBean config) {
        this.config = config;
    }

    public static class MetaBean {
        /**
         * music : {"title":"童话","desc":"光良-童话","preview":"p2.music.126.net/Lezq2-nYThXCmjJ8im18TA==/18809345418066555.jpg","tag":"网易音乐-04:04","musicUrl":"music.163.com/song/media/outer/url?id=85580.mp3","jumpUrl":"music.163.com/song/media/outer/url?id=85580.mp3","appid":101097681,"app_type":1,"source_url":"music.163.com/song/media/outer/url?id=85580.mp3","source_icon":"p2.music.126.net/Lezq2-nYThXCmjJ8im18TA==/18809345418066555.jpg","android_pkg_name":"com.tencent.karaoke"}
         */

        private MusicBean music;

        public MusicBean getMusic() {
            return music;
        }

        public void setMusic(MusicBean music) {
            this.music = music;
        }

        public static class MusicBean {
            /**
             * title : 童话
             * desc : 光良-童话
             * preview : p2.music.126.net/Lezq2-nYThXCmjJ8im18TA==/18809345418066555.jpg
             * tag : 网易音乐-04:04
             * musicUrl : music.163.com/song/media/outer/url?id=85580.mp3
             * jumpUrl : music.163.com/song/media/outer/url?id=85580.mp3
             * appid : 101097681
             * app_type : 1
             * source_url : music.163.com/song/media/outer/url?id=85580.mp3
             * source_icon : p2.music.126.net/Lezq2-nYThXCmjJ8im18TA==/18809345418066555.jpg
             * android_pkg_name : com.tencent.karaoke
             */

            private String title;
            private String desc;
            private String preview;
            private String tag;
            private String musicUrl;
            private String jumpUrl;
            private int appid;
            private int app_type;
            private String source_url;
            private String source_icon;
            private String android_pkg_name;

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }

            public String getDesc() {
                return desc;
            }

            public void setDesc(String desc) {
                this.desc = desc;
            }

            public String getPreview() {
                return preview;
            }

            public void setPreview(String preview) {
                this.preview = preview;
            }

            public String getTag() {
                return tag;
            }

            public void setTag(String tag) {
                this.tag = tag;
            }

            public String getMusicUrl() {
                return musicUrl;
            }

            public void setMusicUrl(String musicUrl) {
                this.musicUrl = musicUrl;
            }

            public String getJumpUrl() {
                return jumpUrl;
            }

            public void setJumpUrl(String jumpUrl) {
                this.jumpUrl = jumpUrl;
            }

            public int getAppid() {
                return appid;
            }

            public void setAppid(int appid) {
                this.appid = appid;
            }

            public int getApp_type() {
                return app_type;
            }

            public void setApp_type(int app_type) {
                this.app_type = app_type;
            }

            public String getSource_url() {
                return source_url;
            }

            public void setSource_url(String source_url) {
                this.source_url = source_url;
            }

            public String getSource_icon() {
                return source_icon;
            }

            public void setSource_icon(String source_icon) {
                this.source_icon = source_icon;
            }

            public String getAndroid_pkg_name() {
                return android_pkg_name;
            }

            public void setAndroid_pkg_name(String android_pkg_name) {
                this.android_pkg_name = android_pkg_name;
            }
        }
    }

    public static class ConfigBean {
        /**
         * forward : true
         * normal : normal
         * autosize : true
         */

        private boolean forward;
        private String normal;
        private boolean autosize;

        public boolean isForward() {
            return forward;
        }

        public void setForward(boolean forward) {
            this.forward = forward;
        }

        public String getNormal() {
            return normal;
        }

        public void setNormal(String normal) {
            this.normal = normal;
        }

        public boolean isAutosize() {
            return autosize;
        }

        public void setAutosize(boolean autosize) {
            this.autosize = autosize;
        }
    }
}